class_name Hand
extends HBoxContainer

const CARD_UI_SCENE := preload("res://scenes/card_ui/card_ui.tscn")

@export var player: Player
@export var char_stats: CharacterStats


func add_card(card: Card) -> void:
	var new_card_ui := CARD_UI_SCENE.instantiate() as CardUI
	add_child(new_card_ui)
	new_card_ui.reparent_requested.connect(_on_card_ui_reparent_requested)
	new_card_ui.card = card
	new_card_ui.parent = self
	new_card_ui.player_modifiers = player.modifier_handler
	
	# 延迟一帧再设置char_stats，确保卡牌UI的可玩性状态检查在正确的时机进行
	# 这样可以避免在贷款状态还未正确设置时就进行可玩性检查
	await get_tree().process_frame
	new_card_ui.char_stats = char_stats
	
	# 立即更新卡牌UI的可玩性状态，确保与当前能量状态同步
	# 使用新的方法，考虑修改器影响
	if new_card_ui.char_stats:
		new_card_ui.playable = new_card_ui.char_stats.can_play_card_with_modifiers(card, player.modifier_handler)
	
	# 更新费用显示，确保考虑当前的修改器状态
	# 通过场景树查找玩家，获取targets数组
	var player_node = player
	if player_node:
		var targets = [player_node]
		new_card_ui.card_visuals.update_cost_display(targets)


func discard_card(card: CardUI) -> void:
	card.queue_free()

# 新增：更新所有手牌中卡牌的费用显示
func update_all_card_costs() -> void:
	var player_node = player
	if not player_node:
		return
	
	var targets = [player_node]
	
	for card_ui in get_children():
		if card_ui is CardUI and card_ui.card_visuals:
			card_ui.card_visuals.update_cost_display(targets)


func disable_hand() -> void:
	for card in get_children():
		card.disabled = true


func _on_card_ui_reparent_requested(child: CardUI) -> void:
	child.disabled = true
	child.reparent(self)
	#卡牌在手牌中的顺序保持不变
	var new_index := clampi(child.original_index, 0, get_child_count())
	move_child.call_deferred(child, new_index)
	child.set_deferred("disabled", false)
